

import router  from './router'
import store from "./store";
import storage from "store";
import NProgress from "nprogress"; // progress bar 进度条
import "@/components/NProgress/nprogress.less"; // progress bar custom style
import { domTitle, setDocumentTitle } from "@/utils/domUtil";
import { ACCESS_TOKEN, USER_INFO } from "@/store/mutation-types";
import { i18nRender } from "@/locales";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const allowList = ["login", "register", "resetpwd", "invitation"]; // no redirect allowList
const loginRoutePath = "/user/login";
const defaultRoutePath = "/welcome";

// 路由守卫
router.beforeEach((to, from, next) => {
  NProgress.start(); // start progress bar  初始化
  to.meta &&
    typeof to.meta.title !== "undefined" &&
      setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`);
  /* has token */
  if (storage.get(ACCESS_TOKEN)) {
    if (to.path === loginRoutePath) {
      storage.remove(ACCESS_TOKEN)
      next({ path: loginRoutePath });
      NProgress.done();
    } else {
      // console.log('路由守卫',store.getters)
      if (store.getters.roles.length === 0) {
        let roles = storage.get(USER_INFO).menuList;
        store.commit("SET_ROLES", roles);
        store.dispatch("GenerateRoutes", roles).then((res) => {
          // 根据roles权限生成可访问的路由表
          // 动态添加可访问路由表
          router.addRoutes(res);
          // 请求带有 redirect 重定向时，登录自动重定向到该地址
          const redirect = decodeURIComponent(from.query.redirect || to.path);
          if (to.path === redirect) {
            next({ ...to, replace: true });
          } else {
            // 跳转到目的路由
            // next({ path: redirect });
            next({ path:to.path});
          }
        });
      } else {
        next();
        // storage.remove(ACCESS_TOKEN)
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next();
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } });
      NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // finish progress bar
});
